import React, { useState } from 'react';
import {
  Form,
  Input,
  Button,
  Modal,
  Select,
  InputNumber,
  DatePicker,
  Popconfirm,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data';
import TableTitle from '../../components/TableTitle';
import { DictItemType, ThemeItemType, PositionType } from './data.d';
import {
  getRightsList,
  addRights,
  getThemeNftList,
  publishRightsIfo,
  deleteRightsIfo,
  getPositionGrades,
} from './service';

// 日期选择器国际化配置
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

const { TextArea } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

export default () => {
  // 控制添加模态框
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  // 权益类型列表
  const [rightsTypes, setRightsTypes] = useState<DictItemType[]>([]);
  // 主题表
  const [themeList, setThemeList] = useState<ThemeItemType[]>();
  // 身份表
  const [position, setPosition] = useState<PositionType[]>([]);

  /**
   * 发布权益
   */
  const publish = async (serialNo: string) => {
    let res = await publishRightsIfo({ serialNo });
    console.log(res);
    actionRef.current?.reload();
  };

  /**
   * 删除权益
   */
  const del = async (serialNo: string) => {
    let res = await deleteRightsIfo({ serialNo });
    console.log(res);
    actionRef.current?.reload();
  };

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      {record.status == '1' ? (
        <>
          <li>
            <Popconfirm
              title="确定发布此权益？"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                publish(record.serialNo);
              }}
            >
              <a>发布</a>
            </Popconfirm>
            <em className="ant-list-item-action-split"></em>
          </li>
          <li>
            <Popconfirm
              title="确定发布此权益？"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                del(record.serialNo);
              }}
            >
              <a>删除</a>
            </Popconfirm>
          </li>
        </>
      ) : null}
    </ul>
  );
  // 自定义数据的表格头部数据
  columnsData.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  /**
   * 搜索主题列表
   */
  const getThemeList = async () => {
    let res = await getThemeNftList({
      current: 1,
      pageSize: 100,
    });
    console.log(res);
    setThemeList(res.data);
  };

  /**
   * 获取身份列表
   */
  const getPosition = async () => {
    let res = await getPositionGrades({});
    console.log(res);
    setPosition(res.data);
  };

  /**
   * 点击新增按钮调用
   */
  const addRightsBtn = async () => {
    console.log('addRightsBtn');
    setIsAddModalVisible(true);
    getThemeList();
    getPosition();
  };

  /**
   * 投放配置模态框确定按钮调用
   */
  const handleAddOk = async () => {
    console.log('handleAddOk');
    // 表单验证
    await addFormRef.validateFields();
    let response = addFormRef.getFieldsValue();
    const {
      description,
      limitedField,
      name,
      number,
      positionNo,
      restrictedPurchase,
      type,
      Time,
    } = response;
    const startTime = Time[0].format('YYYY-MM-DD HH:mm:ss');
    const endTime = Time[1].format('YYYY-MM-DD HH:mm:ss');
    console.log(startTime, endTime);

    console.log(response);
    // let type = Number(response.type);
    let res = await addRights({
      startTime,
      endTime,
      description,
      limitedField,
      name,
      number,
      positionNo,
      restrictedPurchase,
      type,
    });
    console.log(res);
    actionRef.current?.reload();
    setIsAddModalVisible(false);
  };

  /**
   * 投放配置模态框取消按钮调用
   */
  const handleAddCancel = () => {
    addFormRef.resetFields();
    setIsAddModalVisible(false);
    console.log('handleAddCancel');
  };

  // Table action 的引用，便于自定义触发
  const actionRef = React.useRef<ActionType>();
  // 绑定添加规则表单
  const [addFormRef] = Form.useForm();

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title="权益列表" />}
        scroll={{ x: 900 }}
        actionRef={actionRef}
        bordered
        // 表头
        columns={columnsData}
        // 请求获取的数据
        request={async (params) => {
          console.log(params);
          let res = await getRightsList({ ...params });
          console.log('😒', res);
          const result = {
            data: res.data,
            total: res.pagination.totalSize,
          };
          return result;
        }}
        rowKey="serialNo"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        //配置工具栏按钮
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={addRightsBtn}
          >
            添加权益
          </Button>,
        ]}
      />
      {/* 添加单独投放模态框 */}
      <Modal
        title="添加权益"
        centered
        visible={isAddModalVisible}
        onOk={handleAddOk}
        onCancel={handleAddCancel}
        width={700}
      >
        <Form
          name="basic"
          form={addFormRef}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 12 }}
          autoComplete="off"
        >
          <Form.Item
            label="权益名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入权益名称', // 验证失败提示
              },
            ]}
          >
            <Input maxLength={20} />
          </Form.Item>
          <Form.Item
            label="权益类型"
            name="type"
            rules={[
              {
                required: true,
                message: '请选择权益类型', // 验证失败提示
              },
            ]}
          >
            {/* onChange={onRightsTypeChange} */}
            <Select>
              {/* {rightsTypes?.map((item) => (
                <Option key={item.itemValue} value={item.itemValue}>
                  {item.label}
                </Option>
              ))} */}
              <Option value={1}>票务</Option>
              <Option value={2}>商品</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="适用主题"
            name="limitedField"
            rules={[
              {
                required: true,
                message: '请选择适用主题', // 验证失败提示
              },
            ]}
          >
            <Select>
              {themeList?.map((item) => (
                <Option key={item.serialNo} value={item.serialNo}>
                  {item.themeName}
                  {item.sex == 0 ? '(男)' : null}
                  {item.sex == 1 ? '(女)' : null}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="权益数量"
            name="number"
            rules={[
              {
                required: true,
                message: '请输入权益数量', // 验证失败提示
              },
            ]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item
            label="限购数量"
            name="restrictedPurchase"
            rules={[
              {
                required: true,
                message: '请输入限购数量', // 验证失败提示
              },
            ]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item
            label="生效时间"
            name="Time"
            rules={[
              {
                required: true,
                message: '请选择生效时间', // 验证失败提示
              },
            ]}
          >
            <RangePicker
              showTime={{ format: 'HH:mm:ss' }}
              format="YYYY-MM-DD HH:mm:ss"
              locale={locale}
            />
          </Form.Item>
          <Form.Item
            label="权益简介"
            name="description"
            rules={[
              {
                required: true,
                message: '请输入权益简介', // 验证失败提示
              },
            ]}
          >
            <TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
